<template>
  <div class="app-container">
    <el-row :gutter="20" class="question-edit-contain">
      <el-col :span="24">
        <el-card>
          <el-form
            :model="form"
            ref="form"
            label-width="100px"
            v-loading="formLoading"
            :rules="rules"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属人员类型：">
                  <el-select
                    class="filter-item"
                    v-model="form.personnelType"
                    :clearable="true"
                    placeholder=""
                    filterable
                  >
                    <el-option
                      v-for="item in personnelTypeList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属模块">
                  <el-select
                    class="filter-item"
                    v-model="form.moduleType"
                    :clearable="true"
                    placeholder=""
                    filterable
                  >
                    <el-option
                      v-for="item in moduleTypeList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="场景类型">
                  <el-select
                    class="filter-item"
                    v-model="form.sceneType"
                    :clearable="true"
                    placeholder=""
                    filterable
                  >
                    <el-option
                      v-for="item in sceneTypeList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="资料类型">
                  <el-select
                    class="filter-item"
                    v-model="form.materialType"
                    :clearable="true"
                    placeholder=""
                    filterable
                  >
                    <el-option
                      v-for="item in materialTypeList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="资料名称：" prop="materialTitle" required>
              <el-input v-model="form.materialTitle"> </el-input>
            </el-form-item>
            <el-form-item label="资料内容：" prop="materialContent">
              <RichEditor v-model="form.materialContent" @input="handleInput"></RichEditor>
            </el-form-item>
            <el-form-item label="附件：" prop="materialFileUrl">
              <el-upload
                ref="upfile"
                style="display: inline"
                :auto-upload="false"
                :multiple="false"
                :on-change="handleChange"
                :file-list="fileList"
                :on-preview="handlePreview"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :before-upload="beforeUpload"
                :limit="1"
                action="#"
              >
                <el-button type="info">选择文件</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="uploadFile">上传</el-button>
              <el-button type="primary" @click="submitForm">提交</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { DictionaryController, BizMaterialController } from '@/api';
import RichEditor from '@/components/RichEditor/index.vue';
export default {
  name: 'formEditBizMaterial',
  props: {
    rowData: Object
  },
  components: {
    RichEditor
  },
  data() {
    return {
      form: {
        materialId: null,
        personnelType: null,
        moduleType: null,
        materialType: null,
        sceneType: null,
        materialTitle: '',
        materialContent: '',
        materialFileUrl: ''
      },
      personnelTypeList: [],
      moduleTypeList: [],
      materialTypeList: [],
      sceneTypeList: [],
      formLoading: false,
      rules: {
        materialTitle: [{ required: true, message: '请输入资料内容' }]
      },
      fileList: []
    };
  },
  created() {
    this.loadPersonnelTypeDropdownList();
    this.loadModuleTypeDropdownList();
    this.loadMaterialTypeDropdownList();
    this.loadSceneTypeDropdownList();
  },
  methods: {
    handleExceed(file) {
      this.$message.warning('只能上传一个附件');
    },
    handleInput(text) {
      this.form.materialContent = text;
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.fileList = [];
      }
      this.fileList.push(file);
      return true;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
    },
    uploadFile() {
      let fd = {
        file: this.fileList[0].raw
      };
      BizMaterialController.uploadMaterial(this, fd)
        .then(res => {
          this.form.materialFileUrl = res.data.downloadUri + '/' + res.data.filename;
          this.$message.success('附件上传成功');
        })
        .catch(e => {
          console.error('请求失败', e);
          this.$message.error('附件上传失败');
        });
    },
    onCancel(isSuccess = false) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true;
          BizMaterialController.edit(this, this.form)
            .then(re => {
              if (re.errorCode === 'NO-ERROR') {
                this.$message.success('操作成功');
                this.onCancel(true);
                this.$router.replace({ name: 'formsBizMaterial' });
              } else {
                this.$message.error('操作失败');
                console.error(re.errorMessage);
              }
            })
            .finally(() => {
              this.formLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.form = {
        materialId: null,
        personnelType: null,
        moduleType: null,
        materialType: null,
        sceneType: null,
        materialTitle: '',
        materialContent: '',
        materialFileUrl: ''
      };
      this.$refs['form'].resetFields();
    },
    loadPersonnelTypeDropdownList() {
      return new Promise((resolve, reject) => {
        let params = {
          dictCode: 'PersonnelType'
        };
        DictionaryController.dictGlobalDict(this, params)
          .then(res => {
            this.personnelTypeList = res.getList();
          })
          .catch(e => {
            reject(e);
          });
      });
    },
    loadModuleTypeDropdownList() {
      return new Promise((resolve, reject) => {
        let params = {
          dictCode: 'ModuleType'
        };
        DictionaryController.dictGlobalDict(this, params)
          .then(res => {
            this.moduleTypeList = res.getList();
          })
          .catch(e => {
            reject(e);
          });
      });
    },
    loadMaterialTypeDropdownList() {
      return new Promise((resolve, reject) => {
        let params = {
          dictCode: 'MaterialType'
        };
        DictionaryController.dictGlobalDict(this, params)
          .then(res => {
            this.materialTypeList = res.getList();
          })
          .catch(e => {
            reject(e);
          });
      });
    },
    loadSceneTypeDropdownList() {
      return new Promise((resolve, reject) => {
        let params = {
          dictCode: 'SceneType'
        };
        DictionaryController.dictGlobalDict(this, params)
          .then(res => {
            this.sceneTypeList = res.getList();
          })
          .catch(e => {
            reject(e);
          });
      });
    }
  },
  mounted() {
    if (this.rowData != null) {
      this.form.materialId = this.rowData.materialId;
      this.form.personnelType = this.rowData.personnelType + '';
      this.form.moduleType = this.rowData.moduleType + '';
      this.form.materialType = this.rowData.materialType + '';
      if (this.rowData.sceneType) {
        this.form.sceneType = this.rowData.sceneType + '';
      } else {
        this.form.sceneType = null;
      }
      if (this.rowData.materialFileUrl) {
        let index = this.rowData.materialFileUrl.lastIndexOf('/');
        const fileName = this.rowData.materialFileUrl.substring(
          index + 1,
          this.rowData.materialFileUrl.length
        );
        this.fileList = [{ name: fileName, url: this.rowData.materialFileUrl }];
        console.log(this.fileList);
      }
      this.form.materialTitle = this.rowData.materialTitle;
      this.form.materialContent = this.rowData.materialContent;
      this.form.materialFileUrl = this.rowData.materialFileUrl;
    }
  }
};
</script>
<style type="scss" scoped></style>
